//
//  PHWiFiViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2018/3/5.
//  Copyright © 2018年 Levy Xu. All rights reserved.
//

#import "PHWiFiViewController.h"
#import "WifiSave.h"
#import "PHWPTipsViewController.h"
#import "PHAddUtils.h"

@interface PHWiFiViewController ()<QMUITextFieldDelegate, QMUIKeyboardManagerDelegate>
@property (strong, nonatomic) UIImageView *imageView1;
@property (strong, nonatomic) UIImageView *imageView2;
@property (strong, nonatomic) QMUILabel *label1;
@property(nonatomic, strong) QMUITextField *nameTextField;
@property(nonatomic, strong) QMUITextField *pwdTextField;
@property(nonatomic, strong) QMUIFillButton *nextBtn;
@property(nonatomic, strong) QMUIKeyboardManager *keyboardManager;
@end

@implementation PHWiFiViewController

- (void)initSubviews {
    [super initSubviews];
    
    _imageView1 = [[UIImageView alloc] initWithFrame:CGRectZero];
    _imageView1.backgroundColor = [UIColor clearColor];
    _imageView1.image = UIImageMake(@"wifi_connect_in");
    [self.myView addSubview:_imageView1];
    
    _imageView2 = [[UIImageView alloc] initWithFrame:CGRectZero];
    _imageView2.backgroundColor = [UIColor clearColor];
    _imageView2.image = UIImageMake(@"wifi_connect_out");
    [self.myView addSubview:_imageView2];
    
    _label1 = [[QMUILabel alloc] init];
    _label1.font = CodeFontMake(15);
    _label1.textColor = UIColorGray3;
    _label1.textAlignment = NSTextAlignmentCenter;
    _label1.text = NSLocalizedString(@"tips_wifi_password", nil);
    [self.myView addSubview:_label1];
    
    _nameTextField = [[QMUITextField alloc] init];
    _nameTextField.borderStyle = UITextBorderStyleNone;
    _nameTextField.backgroundColor = UIColorClear;
    _nameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _nameTextField.font = CodeFontMake(14);
    _nameTextField.textColor = UIColorBlack;
    _nameTextField.qmui_borderPosition = QMUIBorderViewPositionBottom;
    _nameTextField.enabled = NO;
    _nameTextField.placeholder = NSLocalizedString(@"tips_wifi_connect", nil);
    [self.myView addSubview:_nameTextField];
    
    UIImageView *nameIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    nameIV.image = UIImageMake(@"icon_wifi");
    _nameTextField.leftViewMode = UITextFieldViewModeAlways;
    _nameTextField.leftView = nameIV;
    
    
    _pwdTextField = [[QMUITextField alloc] init];
    _pwdTextField.borderStyle = UITextBorderStyleNone;
    _pwdTextField.returnKeyType = UIReturnKeyDone;
    _pwdTextField.backgroundColor = UIColorClear;
    _pwdTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _pwdTextField.font = CodeFontMake(14);
    _pwdTextField.textColor = UIColorBlack;
    _pwdTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _pwdTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _pwdTextField.placeholder = NSLocalizedString(@"tips_input_password", nil);
    _pwdTextField.secureTextEntry = YES;
    _pwdTextField.delegate = self;
    _pwdTextField.qmui_borderPosition = QMUIBorderViewPositionBottom;
    [self.myView addSubview:_pwdTextField];
    
    UIImageView *pwdIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    pwdIV.image = UIImageMake(@"login_pwd");
    _pwdTextField.leftViewMode = UITextFieldViewModeAlways;
    _pwdTextField.leftView = pwdIV;
    
    QMUIButton *eyeBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [eyeBtn setImage:UIImageMake(@"eye_close") forState:UIControlStateNormal];
    [eyeBtn setImage:UIImageMake(@"eye_open") forState:UIControlStateSelected];
    [eyeBtn addTarget:self action:@selector(eyeAction:) forControlEvents:UIControlEventTouchUpInside];
    _pwdTextField.rightViewMode = UITextFieldViewModeAlways;
    _pwdTextField.rightView = eyeBtn;
    
    _keyboardManager = [[QMUIKeyboardManager alloc] initWithDelegate:self];
    [self.keyboardManager addTargetResponder:_pwdTextField];
    
    _nextBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorRed];
    _nextBtn.titleLabel.font = CodeFontMake(16);
    [_nextBtn setTitle:NSLocalizedString(@"action_next", nil) forState:UIControlStateNormal];
    [_nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:_nextBtn];
}

- (void)viewDidLayoutSubviews {
    self.shouldShowMyView = YES;
    [super viewDidLayoutSubviews];
    
    CGFloat imageWidht = 200.0f;
    CGFloat gap = 20.0f;
    if (IS_35INCH_SCREEN) {
        imageWidht = 160.0f;
        gap = 10.0f;
    }
    
    _imageView1.frame = CGRectMake((self.myView.qmui_width - imageWidht) / 2, gap, imageWidht, imageWidht);
    
    _imageView2.frame = _imageView1.frame;
    
    _label1.frame = CGRectMake(30, _imageView2.qmui_bottom + gap, self.myView.qmui_width - 60, 20);
    
    _nameTextField.frame = CGRectMake(30, _label1.qmui_bottom + gap, self.myView.qmui_width - 60.0f, 40);
    
    _pwdTextField.frame = CGRectMake(30, _nameTextField.qmui_bottom + gap - 10, self.myView.qmui_width - 60, 40);
    
    _nextBtn.frame = CGRectMake(30, _pwdTextField.qmui_bottom + gap + 10, _pwdTextField.qmui_width, 40);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSString *ssid = GetCurrentSSID();
    if (KIsBlankString(ssid)) {
        _nameTextField.text = @"";
        _pwdTextField.text = @"";
        [KKAlert warningWithText:NSLocalizedString(@"tips_wifi_connect", nil)];
    } else {
        _nameTextField.text = ssid;
        _pwdTextField.text = [GWifiSave getKeyBySsid:ssid];
    }
    
    [NNCDC addObserver:self selector:@selector(networkChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [NNCDC removeObserver:self name:AFNetworkingReachabilityDidChangeNotification object:nil];
}

-(void)networkChanged:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    if ([userInfo objectForKey:AFNetworkingReachabilityNotificationStatusItem]) {
        NSInteger staus = [[userInfo objectForKey:AFNetworkingReachabilityNotificationStatusItem] integerValue];
        if (staus == AFNetworkReachabilityStatusReachableViaWiFi) {
            NSString *ssid = GetCurrentSSID();
            _nameTextField.text = ssid;
            _pwdTextField.text = [GWifiSave getKeyBySsid:ssid];
        } else {
            _nameTextField.text = @"";
            _pwdTextField.text = @"";
        }
    }
}

-(void)eyeAction:(QMUIFillButton *)sender {
    sender.selected = !sender.isSelected;
    _pwdTextField.secureTextEntry = !sender.isSelected;
}

-(void)nextAction:(id)sender {
    NSString *ssid = _nameTextField.text;
    if (![QMUIHelper isSimulator] && KIsBlankString(ssid)) {
        [KKAlert warningWithText:NSLocalizedString(@"tips_wifi_connect", nil)];
        return;
    }
    
    NSString *key = _pwdTextField.text;
    [GWifiSave saveSsid:ssid andKey:key];
    
    GPHAddUtils.ssid = ssid;
    GPHAddUtils.key = key;
    
    PHWPTipsViewController *connectVC = [[PHWPTipsViewController alloc] init];
    [self.navigationController pushViewController:connectVC animated:YES];
}

-(void)setupNavigationItems {
    [super setupNavigationItems];
    self.title = NSLocalizedString(@"title_wifi_connect", nil);
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.myView endEditing:YES];
    return YES;
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.myView endEditing:YES];
}

#pragma mark - <QMUIKeyboardManagerDelegate>

- (void)keyboardWillChangeFrameWithUserInfo:(QMUIKeyboardUserInfo *)keyboardUserInfo {
    WS(ws);
    [QMUIKeyboardManager handleKeyboardNotificationWithUserInfo:keyboardUserInfo showBlock:^(QMUIKeyboardUserInfo *keyboardUserInfo) {
        [QMUIKeyboardManager animateWithAnimated:YES keyboardUserInfo:keyboardUserInfo animations:^{
            CGFloat distance = [QMUIKeyboardManager distanceFromMinYToBottomInView:ws.pwdTextField keyboardRect:keyboardUserInfo.endFrame];
            if (distance > 0) {
                ws.view.layer.transform = CATransform3DMakeTranslation(0, - distance, 0);
            }
        } completion:NULL];
    } hideBlock:^(QMUIKeyboardUserInfo *keyboardUserInfo) {
        [QMUIKeyboardManager animateWithAnimated:YES keyboardUserInfo:keyboardUserInfo animations:^{
            ws.view.layer.transform = CATransform3DIdentity;
        } completion:NULL];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
